var Web3 = require("web3");
var web3 = new Web3();
web3.setProvider(new Web3.providers.HttpProvider("http://localhost:8545"));
var Tx = require('ethereumjs-tx').Transaction;

//发普通交易
sendSignedTransaction();

function sendSignedTransaction(){
	var privateKey = Buffer.from('da31646d3239fc8a772585ede15441173b52e0c63ed5f9bc14b02539345e2791', 'hex');
	var fromAddress = '0x10Db1Bf1759164b22B347092Bf7e343C1aFd6787';
	var toAddress = '0xa8FE05a7574f6E99e9a4f439607Ce12e8391f8FE';
	var initData = '0x123456';
   web3.eth.getTransactionCount(fromAddress, 'pending',(err, nonce)=>{
	if(err){
		console.log(err)
	}
	 var rawTx = {
	  nonce: web3.utils.toHex(nonce),
	   gasPrice: web3.utils.toHex(web3.utils.toWei('20','gwei')),
	   gasLimit: web3.utils.toHex('3000000'),
	   from: fromAddress,
	   to: toAddress,
	   data: initData,
	   value: web3.utils.toHex(2)
	 }
	 var tx = new Tx(rawTx);
	 tx.sign(privateKey);
	 	
	 var serializedTx = tx.serialize();
	
	web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'),(error,hash)=>{
		if(!error){
			console.log(hash)
		}else{
			console.log(error)
		}
	})
})


//获取eth余额
web3.eth.getBalance(fromAddress).then(console.log); 
web3.eth.getBalance(toAddress).then(console.log); 
}

